package com.usian.controller;

import com.usian.pojo.User;
import com.usian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findAll")
    public String findAll(Model model){

        List<User> list = userService.findAll();
        model.addAttribute("list",list);
        return "index";
    }

    @RequestMapping("/add")
    public void add(User user, HttpServletResponse response){

        try {
            userService.insert(user);
            response.sendRedirect("/user/findAll");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/toadd")
    public String toadd(){
        return "add";
    }


    @RequestMapping("/findById")
    public String findById(Integer id, Model model){
        User user = userService.findById(id);
        model.addAttribute("user",user);
        int[] ints = new int[5];
        int [] a = {};
        return "update";

    }

    @RequestMapping("/delete")
    public void delete(Integer id,HttpServletResponse response){

        try {
            userService.delete(id);
            response.sendRedirect("/user/findAll");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/update")
    public void update(User user,HttpServletResponse response){
        try {
            userService.update(user);
            response.sendRedirect("/user/findAll");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
